package com.enbatis.dynamic.datasource.autoconfigure.dynamic;

import com.enbatis.dynamic.datasource.autoconfigure.dynamic.annotation.DynamicTx;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import java.lang.reflect.Method;

/**
 * @author wwd
 */
@Component
@Aspect
@Order(2)
public class DynamicTransactionAspect {

    private Logger logger = LoggerFactory.getLogger(DynamicTransactionAspect.class);
    @Autowired
    private JtaTransactionManager jtaTransactionManager;

    /**
     *
     */
    @Pointcut("@annotation(com.enbatis.dynamic.datasource.autoconfigure.dynamic.annotation.DynamicTx)")
    public void transactionPointCut() {
    }

    /**
     * @param point
     */
    @Around("transactionPointCut()")
    public Object around(ProceedingJoinPoint point) {

        Object object = null;
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DynamicTx annotation = method.getAnnotation(DynamicTx.class);
        if (annotation != null) {
            String className = point.getTarget().getClass().getName();
            String methodName = signature.getName();
            System.out.println("method is:" + className + "." + methodName + "()");

            try {
                jtaTransactionManager.getUserTransaction().begin();
            } catch (NotSupportedException e) {
                e.printStackTrace();
            } catch (SystemException e) {
                e.printStackTrace();
            }
            try {
                object = point.proceed();
                jtaTransactionManager.getUserTransaction().commit();

                logger.info("Transaction commit");
            } catch (Throwable throwable) {
                logger.error("Transaction failed ..."+throwable.getMessage());
                try {
                    logger.info("Transaction start rollback ");
                    jtaTransactionManager.getUserTransaction().rollback();
                    logger.info("Transaction start rollback ");
                } catch (SystemException e) {
                    e.printStackTrace();
                }
            }
        }
        return object;
    }


}
